package com.edroid.swingtest;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class ContentPaneTest extends JApplet {
	private JButton button = new JButton("show glass pane");

	public void init() {
		setGlassPane(new CustomGlassPane2(button));
		setContentPane(new CustomContentPane(button));

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getGlassPane().setVisible(true);
			}
		});
	}
}

class CustomContentPane extends JPanel {
	private ImageIcon rain = new ImageIcon("rain.gif");
	private ImageIcon punch = new ImageIcon("punch.gif");
	private int rainw = rain.getIconWidth();
	private int rainh = rain.getIconHeight();

	public CustomContentPane(JButton button) {
		add(button);
		add(new JLabel("I'm a JLabel in the Content Pane", punch,
				SwingConstants.RIGHT));
	}

	public void paintComponent(Graphics g) {
		Dimension size = getSize();

		for (int row = 0; row < size.height; row += rainh)
			for (int col = 0; col < size.width; col += rainw)
				rain.paintIcon(this, g, col, row);
	}
}

class CustomGlassPane2 extends JPanel {
	private JButton button;
	private Point ulhc = new Point(20, 20), last;
	private String displayString = "I'm on the glass pane - drag me around!";

	public CustomGlassPane2(JButton b) {
		button = b;

		setOpaque(false);
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				last = e.getPoint();
			}

			public void mouseReleased(MouseEvent e) {
				setVisible(false);
			}
		});
		addMouseMotionListener(new MouseMotionAdapter() {
			public void mouseDragged(MouseEvent e) {
				Point drag = e.getPoint();
				ulhc.x += drag.x - last.x;
				ulhc.y += drag.y - last.y;

				repaint();

				last.x = drag.x;
				last.y = drag.y;
			}
		});
	}

	public void paintComponent(Graphics g) {
		FontMetrics fm = g.getFontMetrics();
		int sw = fm.stringWidth(displayString);
		int sh = fm.getHeight();
		int ascent = fm.getAscent();

		g.drawRect(ulhc.x, ulhc.y, sw + 10, sh + 10);
		g.drawString(displayString, ulhc.x + 5, ulhc.y + ascent + 5);
	}
}
